package com.atguigu.flink.aggregation;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorKeySelector;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class AggReduce {
    public static void main(String[] args) throws Exception {

        // TODO 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // TODO 从指定端口获取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);

        // TODO 类型转换
        SingleOutputStreamOperator<WaterSensor> mapDs = socketDS.map(new WaterSensorMapFunction());

        // TODO 按照id分组
        KeyedStream<WaterSensor, String> keyByDs = mapDs.keyBy(new WaterSensorKeySelector());

        // TODO 对vc进行归并
        SingleOutputStreamOperator<WaterSensor> reduceDs = keyByDs.reduce(new ReduceFunction<WaterSensor>() {
            @Override
            public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                value1.setVc(value1.getVc() + value2.getVc());
                return value1;
            }
        });

        // TODO 打印
        reduceDs.print();

        // TODO 提交作业
        env.execute();
    }
}
